package com.example.service.impl;/**
 * @author wangXiao
 */

import com.example.entity.ConfigBean;
import com.example.entity.QueryPermissionVo;
import com.example.entity.ReadMeConfig;
import com.example.entity.base.BaseResult;
import com.example.mapper.UserMapper;
import com.example.service.SakuraService;
import com.example.twoDataSource.inter.DS;
import com.example.util.ConfigClass;
import com.example.util.ConfigParser;
import com.example.util.SpringBeanUtil;
import com.example.util.TaskListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author wangXiao
 * @Date 2021/9/6
 **/
@Service
@Slf4j
public class SakuraServiceImpl implements SakuraService {

    @Resource
    UserMapper userMapper;

    private AbstractExecutionThreadService service;

 /*   @Autowired
    private ThreadPoolTaskExecutor taskExecutor;*/

    @Resource
    private ConfigClass configClass;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public List<String> selectUsers() {
        Map<String,Object> param = new HashMap<>();
        //方式1 直接注入applicationContext
        OrderTaskServic orderTaskServic = (OrderTaskServic)applicationContext.getBean(OrderTaskServic.class);
        orderTaskServic.cancelOrder();
        //方式2 通过SpringBeanUtil获取
        TranTest2Service test2Service = (TranTest2Service) SpringBeanUtil.getBean(TranTest2Service.class);
        test2Service.sendMessage1();
        param.put("a", "1");
        Object object=new Object();
        return userMapper.selectUser(param);
    }

    private final static ImmutableMap<String, String> TASK_MAP;

    static {
        ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
        Enumeration<URL> urls;
        try {
            urls = Thread.currentThread().getContextClassLoader().getResources("META-INF/version-config.yml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        URL url = urls.nextElement();
        Map<String, Object> config = null;
        try {
            config = (Map<String, Object>) (new Yaml().load(url.openStream()));
            List<String> tasks = (List<String>) config.get("tasks");
            for (String task : tasks) {
                builder.put(task, task);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        TASK_MAP = builder.build();
    }

    @Override
    public void getReadmeConfig() throws IOException {
        File directory = new File("src/main/resources");
        String reportPath = directory.getCanonicalPath();
        ReadMeConfig readMeConfig = ConfigParser.parse(new File(reportPath, "README.yml"));
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(readMeConfig));
        System.out.println(readMeConfig);

        Supplier<TaskListener> taskListener = createTaskListenerSupplier();

        com.google.common.util.concurrent.Service.Listener serviceListener = new com.google.common.util.concurrent.Service.Listener() {
            @Override
            public void starting() {

                System.out.println("----starting----");
            }

            @Override
            public void terminated(com.google.common.util.concurrent.Service.State from) {
                System.out.println("----terminated---");
            }

            @Override
            public void failed(com.google.common.util.concurrent.Service.State from, Throwable failure) {
                System.out.println("----升级失败----");
            }
        };

        service = new MulTaskService(null, readMeConfig.getTaskInstances(), readMeConfig.getTasks(), taskListener);
       // service.addListener(serviceListener, taskExecutor);
        service.startAsync();

    }

    @Override
    public void getConfigBeanPropertY(ConfigBean configBean) {
        System.out.println(configBean.getConfigName());
    }

    private List<QueryPermissionVo> listTreeMenu() {
        return userMapper.getAllMenuList();
    }

    @Override
    public List<QueryPermissionVo> treeMenuList() {
        return buildMenuTree();
    }

    @Override
    @Cacheable(value = "student00",key = "#param")
    public List<String> getCacheTest(String param) {
        List<String> list = new ArrayList<>();
        list.add(selectUsers().get(0));
        return list;
    }

    @Override
    @DS("db1")
    public void getdataSource1() {
        List<String> list =  userMapper.getDataSourece1();
        System.out.println(Arrays.toString(list.toArray()));
    }

    @Override
    @DS("db2")
    public void getdataSource2() {
        List<String> list =  userMapper.getDataSourece2();
        System.out.println(Arrays.toString(list.toArray()));
    }

    public List<QueryPermissionVo> buildMenuTree() {
        List<QueryPermissionVo> allMenuList = userMapper.getAllMenuList();
        //找到根节点，递归组装每个节点的子节点的菜单
        List<QueryPermissionVo> menuTree = allMenuList.stream().filter(item -> item.getPid() == -1L).map(item -> {
            item.setChilds(getChildrens(item, allMenuList));
            return item;
        }).sorted((menu1, menu2) -> {
            // 2、菜单的排序
            return (menu1.getOrders() == null ? 0 : menu1.getOrders())
                    - (menu2.getOrders() == null ? 0 : menu2.getOrders());
        }).collect(Collectors.toList());
        return menuTree;
    }

    private List<QueryPermissionVo> getChildrens(QueryPermissionVo item, List<QueryPermissionVo> allMenuList) {
        //遍历所有的菜单项找到当前菜单的子菜单，然后递归直到所有的都找完
        List<QueryPermissionVo> children = allMenuList.stream().filter(menu -> String.valueOf(menu.getPid()).equals(String.valueOf(item.getPermissionId())))
                .map(menu->{
                    try {
                        menu.setChilds(getChildrens(menu, allMenuList));
                    } catch (Exception e) {
                        System.out.println(menu.getName());
                        e.printStackTrace();
                    }
                    return menu;
        }).collect(Collectors.toList());
        return children;
    }


    private Supplier<TaskListener> createTaskListenerSupplier() {
        return () -> new TaskListener() {

        };
    }

    /**
     * 更新
     */


    @Override
    public BaseResult testTransactional(String str) {
        if(!str.equals("1")){
            return  BaseResult.newError("参数错误");
        }else{
            userMapper.insertUser(str);
            return  BaseResult.newSuccess();
        }
    }
}
